package com.filldream.fastboot.common.okutil.stock.cf.comment;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.filldream.fastboot.common.okutil.stock.cf.comment.dto.CfComment;
import com.filldream.fastboot.common.okutil.stock.cf.comment.dto.CfCommentReply;
import com.filldream.fastboot.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 东方财富网-工具
 *
 * @version 2.0
 */
@Slf4j
public class CfCommentUtil {

    /**
     * 获取评论
     *
     * @param code
     * @return
     */
    public static List<CfComment> getComments(String code) {
        List<CfComment> resultList = new ArrayList<>();
        try {
            int sortType = RandomUtil.randomInt(0, 2);
            String httpResult = HttpUtil.get("https://gbapi.eastmoney.com/webarticlelist/api/article/WebArticleList?code="
                    + code + "&p=1&ps=40&plat=web&version=300&product=guba&deviceid=1"
                    + "&sorttype=" + sortType
                    + "&rrr=" + RandomUtil.randomInt(10, 999));
            //转换对象
            JSONObject jsonObject = JSONObject.parseObject(httpResult);
            String stockName = jsonObject.getJSONObject("bar_info").getString("ShortName");
            String stockCode = jsonObject.getJSONObject("bar_info").getString("AppCode");
            String theme = "$" + stockName + "(" + stockCode + ")$";
            resultList = JsonUtil.fromJosnArray(jsonObject.getJSONArray("re").toJSONString(), CfComment.class);
            resultList = resultList.stream()
                    .sorted(Comparator.comparing(CfComment::getPost_publish_time))
                    .collect(Collectors.toList());
            resultList.forEach(item -> {
                item.setSearchCode(code);
                item.setTheme(theme);
                item.setStockName(stockName);
                List<CfCommentReply> replyList = item.getReply_list();
                if (ObjectUtils.isNotEmpty(replyList)) {
                    item.setReply_list(replyList.stream()
                            .sorted(Comparator.comparing(CfCommentReply::getReply_time))
                            .collect(Collectors.toList()));
                }
                item.setChannelType(1);
            });
            resultList = resultList.stream()
                    .sorted(Comparator.comparing(CfComment::getPost_publish_time))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("请求东方财富网股吧股评失败", e);
        }
        return resultList;
    }


}
